import resources.Constants;
import registnet.dao.DegreeCoursePeer;
import registnet.dao.CollegePeer;
import registnet.dao.UnitPeer;
import registnet.dao.CoursePeer;
import registnet.dao.DegreeCourse;
import registnet.dao.SystemProperties;
import registnet.dao.Unit;
import registnet.dao.Course;

DegreeCoursePeer degreeCoursePeer = new DegreeCoursePeer();
CoursePeer coursePeer = new CoursePeer();
Unit daoUnit = new Unit();
SystemProperties systemProperties = new registnet.dao.SystemPropertiesPeer().getSystemProperties();

String instance = "Pre-Enlistment";

/* [start] 	initializes gui variables */

	RegistNetPropertyBundle bundle = RegistNetPropertyBundle.getInstance("/resources/registnet");
	
/* [end] */


/* [start]	prepares the tree */

	ArrayList parentList = new ArrayList();
	Map mapSTN_parent = new HashMap();
	Map mapAL_parent = new HashMap();
	Map mapAL_child = new HashMap();
	Map map_treeitem = new HashMap();
	SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);
	
/* [end] */


/* [start]	defines the renderer for the tree */

	public class MyTreeitemRenderer implements TreeitemRenderer {
		public void render(Treeitem item, Object data) throws Exception {
			String str = data.toString();
			Treerow tr = null;
			Treecell tc = new Treecell(str);
			if(item.getTreerow()==null){
				tr = new Treerow();
				tr.setParent(item);
				map_treeitem.put(str, item);
			}else{
				tr = item.getTreerow(); 
				tr.getChildren().clear();
			}
			tc.setParent(tr);
		}
	}
	
/* [end] */


/* [start]	retrieves the degree courses and places them on the tree;
			limits the degree courses to retrieve depending on the user type */
			
	public void retrieveObjects(){
		map_treeitem.clear();
		mapSTN_parent.clear();
		mapAL_parent.clear();
		mapAL_child.clear();
		parentList.clear();
		
		if(instance.equals("Pre-Enlistment")){
			tree_label.setLabel("Units");
			
			List colleges = new Vector();
			colleges = new CollegePeer().getAllColleges();
			
			for(int i=0; i<colleges.size(); i++){
				List units;
				units = new UnitPeer().getUnitByCollege(colleges.get(i).getCollegeId());
				ArrayList alChild = new ArrayList();
				ArrayList alLeaf = new ArrayList();
				for(int j=0; j<units.size(); j++){
					SimpleTreeNode stnChild = new SimpleTreeNode(units.get(j).getUnitCode(), new ArrayList());
					alLeaf.add(units.get(j).getUnitCode());
					alChild.add(stnChild);
				}
				SimpleTreeNode stnParent = new SimpleTreeNode(colleges.get(i).getCollegeCode(), alChild);
				mapSTN_parent.put(colleges.get(i).getCollegeCode(), stnParent);
				mapAL_parent.put(colleges.get(i).getCollegeCode(), alChild);
				mapAL_child.put(colleges.get(i).getCollegeCode(), alLeaf);
				parentList.add(stnParent);
			}
		
		}
		
		else{
			tree_label.setLabel("Degree Programs");
			List colleges = new Vector();
			colleges = new CollegePeer().getAllColleges();
			
			for(int i=0; i<colleges.size(); i++){
				List degrees = degreeCoursePeer.getDegreeCourseByCollege(colleges.get(i).getCollegeId());
				ArrayList alChild = new ArrayList();
				ArrayList alLeaf = new ArrayList();
				for(int j=0; j<degrees.size(); j++){
					SimpleTreeNode stnChild = new SimpleTreeNode(degrees.get(j).getDegreeCode(), new ArrayList());
					alLeaf.add(degrees.get(j).getDegreeCode());
					alChild.add(stnChild);
				}
				SimpleTreeNode stnParent = new SimpleTreeNode(colleges.get(i).getCollegeCode(), alChild);
				mapSTN_parent.put(colleges.get(i).getCollegeCode(), stnParent);
				mapAL_parent.put(colleges.get(i).getCollegeCode(), alChild);
				mapAL_child.put(colleges.get(i).getCollegeCode(), alLeaf);
				parentList.add(stnParent);
			}
			
		}
		
		SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);
		SimpleTreeModel stm = new SimpleTreeModel(root);
		instance_tree.setModel(stm);
		instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
	}
	
/* [end] */


/* [start]	defines an event listener for the items on the tree;
			when the item is selected, its info is displayed */
			
	private class SelectEventListener implements EventListener {	
		public SelectEventListener (){}
		
		public void onEvent(Event event) throws UiException {
			showInfo();
		}
	}
	
/* [end] */


/* [start] displays the info of the selected item */

	void showInfo(){
		isShowingInfo = true;
		isSearching = false;
		try{
			if (instance_tree.getSelectedCount() == 1){
				if (instance_tree.getSelectedItem().getParentItem() != null){
					degreeCourse = degreeCoursePeer.getDegreeCourse(instance_tree.getSelectedItem().getLabel());
					loadContents(title.getValue(),degreeCourse);
				}
				else
					title.setValue(title.getValue());	
			}
		}catch (Exception e) { }
	}
	
/* [end] */

/* [start] update estimated demand */

	void update(String courseCode, Integer estimatedDemand){
		registnet.dao.Course daoCourse = new registnet.dao.CoursePeer().getCourse(courseCode);
		try{
			new registnet.dao.CourseDemandPeer().updateCourseDemand(daoCourse.getCourseId(), estimatedDemand);
		}catch(Exception e){
		}
	}
	
/* [end] */


/* [start]	summary renderer */

	private class TableRenderer implements ListitemRenderer  {
		public void render(Listitem item, java.lang.Object data) {
			new Listcell(data[0]).setParent(item);
			new Listcell(data[1]).setParent(item);
			new Listcell(data[2]).setParent(item);
			new Listcell(data[3]).setParent(item);
		}
	}
	
/* [end] */

/* [start]	frequency renderer */

	private class FrequencyRenderer implements ListitemRenderer  {
		public void render(Listitem item, java.lang.Object data) {
			new Listcell(data[0]).setParent(item);
			new Listcell(data[1]).setParent(item);
			new Listcell(data[2]).setParent(item);
		}
	}

/* [end] */


/* [start]	frequency renderer */

	private class Grid4Renderer implements RowRenderer  {
		public void render(Row row, java.lang.Object data) {
			new Label(data[0]).setParent(row);
			new Label(data[1]).setParent(row);
			new Label(data[2]).setParent(row);
			Hbox hbox = new Hbox();
				Intbox intbox = new Intbox(Integer.parseInt(data[3]));
				intbox.setWidth("60px");
				intbox.setParent(hbox);
				Button button = new Button("Save");
				button.addEventListener("onClick",new EventListener(){
						public void onEvent(Event event) throws UiException {
							update(data[0],new Integer(event.getTarget().getParent().getFirstChild().getValue()));
						}
					});
				button.setParent(hbox);
			hbox.setParent(row);
		}
	}

/* [end] */


/* [start] load contents of table */
	
	void loadContents(String type, DegreeCourse degreeCourse){
	
		if(type.equals("Pre-Enlistment")){
		
			daoUnit = new UnitPeer().getUnit(instance_tree.getSelectedItem().getLabel());
			List courses = coursePeer.getCoursesByUnit(daoUnit.getUnitId());
			ListIterator li = courses.listIterator();
			String[][] strArr = new String[courses.size()][4];
			
			for(int i=0; i<courses.size(); i++){
				Course course = (Course)li.next();
				strArr[i][0] = course.getCourseCode();
				strArr[i][1] = course.getCourseName();
				int demand = 0;
				try{
					demand = new registnet.dao.CourseDemandPeer().getCourseDemand(course.getCourseId()).getActualDemand();
				}catch(Exception e){  }
				strArr[i][2] = "" + demand;
				demand = 0;
				try{
					demand = new registnet.dao.CourseDemandPeer().getCourseDemand(course.getCourseId()).getEstimatedDemand();
				}catch(Exception e){  }
				strArr[i][3] = "" + demand;
			}
		
			ListModel strset = new SimpleListModel(strArr);
			contents.getFellow("courseDemand_grid").setModel(strset);
			contents.getFellow("courseDemand_grid").setRowRenderer(new Grid4Renderer());
			return;
		}
		
		registnet.dao.StudentPeer daoStudentPeer = new registnet.dao.StudentPeer();
		List listDaoStudents;
		String[][] listModel;
		
		if(type.equals("Student Standing")){
		
			listDaoStudents = daoStudentPeer.getActiveStudentsByDegree(degreeCourse.getDegreeId());
			ListIterator li = listDaoStudents.listIterator();
			listModel= new String[listDaoStudents.size()][4];
			
			int ctr=0;
			while(li.hasNext()){
				registnet.dao.Student daoStudent;
				try{
					daoStudent = (registnet.dao.Student)li.next();
					listModel[ctr][0] = daoStudent.getStudentNumber();
					listModel[ctr][1] = daoStudent.getFirstName();
					listModel[ctr][2] = daoStudent.getLastName();
					try{ listModel[ctr][3] = Constants.MAP_STANDING_KEY.get(new registnet.dao.StudentStandingPeer().getStudentStanding(daoStudent.getStudentId(), systemProperties.getSemester(), systemProperties.getAcademicYear()).getStanding()); }
					catch(Exception e){ listModel[ctr][3] = ""; }
					
				}catch(Exception e){
					System.err.println(e.getMessage());
					continue;
				}
				ctr++;
			}
		
		}
		
		else if(type.equals("Student Classification")){
		
			listDaoStudents = daoStudentPeer.getActiveStudentsByDegree(degreeCourse.getDegreeId());
			ListIterator li = listDaoStudents.listIterator();
			listModel= new String[listDaoStudents.size()][4];
			
			int ctr=0;
			while(li.hasNext()){
				registnet.dao.Student daoStudent;
				try{
					daoStudent = (registnet.dao.Student)li.next();
					listModel[ctr][0] = daoStudent.getStudentNumber();
					listModel[ctr][1] = daoStudent.getFirstName();
					listModel[ctr][2] = daoStudent.getLastName();
					try{ listModel[ctr][3] = Constants.MAP_CLASSIFICATION_KEY.get(new registnet.dao.StudentClassificationPeer().getStudentClassification(daoStudent.getStudentId(), systemProperties.getSemester(), systemProperties.getAcademicYear()).getClassification()); }
					catch(Exception e){ listModel[ctr][3] = "";  }
					
				}catch(Exception e){
					System.err.println(e.getMessage());
					continue;
				}
				ctr++;
			}
		
		}
		
		else if(type.equals("Student Priority")){
		
			listDaoStudents = daoStudentPeer.getActiveStudentsByDegree(degreeCourse.getDegreeId());
			ListIterator li = listDaoStudents.listIterator();
			listModel= new String[listDaoStudents.size()][4];
			
			int ctr=0;
			while(li.hasNext()){
				registnet.dao.Student daoStudent;
				try{
					daoStudent = (registnet.dao.Student)li.next();
					listModel[ctr][0] = daoStudent.getStudentNumber();
					listModel[ctr][1] = daoStudent.getFirstName();
					listModel[ctr][2] = daoStudent.getLastName();
					try{ listModel[ctr][3] = "Level " + new registnet.dao.StudentPriorityPeer().getStudentPriority(daoStudent.getStudentId()).getLevel(); }
					catch(Exception e){ listModel[ctr][3] = ""; }
					
				}catch(Exception e){
					System.err.println(e.getMessage());
					continue;
				}
				ctr++;
			}
		
		}
		
		else if(type.equals("Recommended Courses")){
		
			listDaoStudents = daoStudentPeer.getActiveStudentsByDegree(degreeCourse.getDegreeId());
			ListIterator li = listDaoStudents.listIterator();
			listModel= new String[listDaoStudents.size()][4];
			
			int ctr=0;
			while(li.hasNext()){
				registnet.dao.Student daoStudent;
				try{
					daoStudent = (registnet.dao.Student)li.next();
					listModel[ctr][0] = daoStudent.getStudentNumber();
					listModel[ctr][1] = daoStudent.getFirstName();
					listModel[ctr][2] = daoStudent.getLastName();
					listModel[ctr][3] = "";
					try{
						ListIterator li0 = new registnet.dao.StudentRecommendedCoursePeer().getRecommendedCoursesByStudent(daoStudent.getStudentId()).listIterator();
						while(li0.hasNext()){
							listModel[ctr][3] = listModel[ctr][3] + "'" + ((registnet.dao.StudentRecommendedCourse)li0.next()).getCourse().getCourseCode() + "' ";
						}
					}
					catch(Exception e){listModel[ctr][3] = ""; }
					
				}catch(Exception e){
					System.err.println(e.getMessage());
					continue;
				}
				ctr++;
			}
		
		}
		
		ListModel strset = new SimpleListModel(listModel);
		contents.getFellow("listbox_content").setModel(strset);
		contents.getFellow("listbox_content").setItemRenderer(new TableRenderer());
		
	}
	
/* [end] */


/* [start] 	show student standing */

	void showStanding(){
		if (contents.getFirstChild() != null){
			contents.removeChild(contents.getFirstChild());
		}
		contents.appendChild(Executions.createComponents("../../WEB-INF/macros/registration/standing.zul", contents, null));
		title.setValue("Student Standing");
		instance = "Student Standing";
		retrieveObjects();
		showInfo();
	}
	
/* [end] */


/* [start] 	show student classification */

	void showClassification(){
		if (contents.getFirstChild() != null){
			contents.removeChild(contents.getFirstChild());
		}
		contents.appendChild(Executions.createComponents("../../WEB-INF/macros/registration/classification.zul", contents, null));
		title.setValue("Student Classification");
		instance = "Student Classification";
		retrieveObjects();
		showInfo();
	}
	
/* [end] */


/* [start] 	show student priority */

	void showPriority(){
		if (contents.getFirstChild() != null){
			contents.removeChild(contents.getFirstChild());
		}
		contents.appendChild(Executions.createComponents("../../WEB-INF/macros/registration/priority.zul", contents, null));
		title.setValue("Student Priority");
		instance = "Student Priority";
		retrieveObjects();
		showInfo();
	}
	
/* [end] */


/* [start] 	show recommended courses */

	void showRecommendedCourses(){
		if (contents.getFirstChild() != null){
			contents.removeChild(contents.getFirstChild());
		}
		contents.appendChild(Executions.createComponents("../../WEB-INF/macros/registration/recommended_courses.zul", contents, null));
		title.setValue("Recommended Courses");
		instance = "Recommended Courses";
		retrieveObjects();
		showInfo();
	}
	
/* [end] */


/* [start] 	show preenlistment */

	void showPreenlistment(){
		if (contents.getFirstChild() != null){
			contents.removeChild(contents.getFirstChild());
		}
		contents.appendChild(Executions.createComponents("../../WEB-INF/macros/registration/preregistrationform.zul", contents, null));
		title.setValue("Pre-Enlistment");
		instance = "Pre-Enlistment";
		retrieveObjects();
		showInfo();
	}
	
/* [end] */






